import time

from django.contrib import admin

# Register your models here.
from django.urls import reverse
from django.utils.html import format_html

from user_app.models import User
from utils.encode_decode import bw_encode


@admin.register(User)
class UserAdmin(admin.ModelAdmin):
    list_display = ('nick_name', 'email', 'my_add_time', 'my_last_login_time', 'my_is_delete', 'my_is_valid', 'level', 'info')
    fields = ('nick_name', 'email', 'password', 'level')

    list_display_links = ['nick_name']
    list_filter = ['email', 'nick_name']
    search_filter = ['email', 'nick_name']
    actions = ['delete_item']
    # list_per_page设置每页显示多少条记录，默认是100条
    list_per_page = 50
    # ordering设置默认排序字段，负号表示降序排序
    ordering = ('-register_time',)
    # list_editable 设置默认可编辑字段
    list_editable = ['email', 'info']
    actions_on_top = True
    actions_on_bottom = True
    save_on_top = False

    def delete_item(modeladmin, request, queryset):
        for i in queryset:
            i.delete()
        return modeladmin.message_user(request, f'成功删除{len(queryset)}条记录')

    delete_item.short_description = '删除已选项'

    def save_model(self, request, obj, form, change):
        obj.password = bw_encode(obj.password)  # 修改密码值为hex
        return super().save_model(request, obj, form, change)

    @staticmethod
    def get_add_time(time_):
        time_array = time.localtime(time_)  # 转换为可用的时间，就是下面的%Y %m %d
        day_time = time.strftime('%Y-%m-%d %H:%M:%S', time_array)  # 取上面的timeArray中的对应值0
        return day_time

    def my_is_delete(self, obj):
        """自定义列表字段"""
        ret = "已注销" if obj.is_delete else "正常"
        return ret

    my_is_delete.short_description = '是否注销'

    def my_is_valid(self, obj):
        """自定义列表字段"""
        ret = "已禁用" if not obj.is_valid else "正常"
        return ret

    my_is_valid.short_description = '是否禁用'

    def my_add_time(self, obj):
        """自定义列表字段"""
        ret = self.get_add_time(obj.register_time)
        return ret

    my_add_time.short_description = '注册时间'

    def my_last_login_time(self, obj):
        """自定义列表字段"""
        ret = self.get_add_time(obj.last_login_time)
        return ret

    my_last_login_time.short_description = '上次登录时间'



